<script setup lang="ts">
// import { useWindowSize } from "@vueuse/core";
import { onMounted, reactive, ref, onUpdated, onUnmounted, watch } from "vue";
import { ElButton, ElMessageBox, ElMessage } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import AddFill from "@iconify-icons/ri/add-circle-line";
import dialogFormNew from "./components/DialogFormNew.vue";

import {
  VideoPlay,
  InfoFilled,
  SwitchButton,
  Loading,
  FolderOpened
} from "@element-plus/icons-vue";
import splitpane, { ContextProps } from "@/components/ReSplitPane";
import Line from "./components/Line.vue";
import Contor from "./components/Contor.vue";
import contordialog from "./components/ContorDialog.vue";
import expinfo from "./components/expInfo.vue";
import { useRoute } from "vue-router";
import {
  getPlatform,
  updatePlatform,
  LabPlatformVO
} from "@/api/LabPlatformApi";
import {
  SettingIF,
  ContorDevice,
  downloadInstanceData
} from "@/api/LabInstanceApi";
import { getRunningExperiments } from "@/api/LabExperimentApi";
import { listDeviceStatus } from "@/api/deviceApi";

// import { SpeedDialComponent as EjsSpeeddial } from "@syncfusion/ej2-vue-buttons";
// import fab from "vue-fab";
import router from "@/router";
import {
  Experiment,
  getExperiment,
  startInstance,
  stopInstance,
  removeExpDevice,
  updateInstance,
  updateInstanceExt
} from "@/api/LabExperimentApi";
import { message } from "@/utils/message";
import { useExpInsHook } from "@/store/modules/expIns";
import { resolve } from "path";
import data from "@iconify-icons/ri/fullscreen-fill";

const { query } = useRoute();
// const expInstName = ref(query.name ? query.name : "");
const expInstId = ref(query.id ? query.id : "");
const configId = ref(query.configId ? query.configId : "");
const configFlag = ref(query.configFlag ? query.configFlag : "");
const hisFlag = ref(query.hisFlag ? query.hisFlag : "");
const expFlag = ref(query.expFlag ? query.expFlag : "");

// const labPlatformVO = ref<Partial<LabPlatformVO>>({ sensors: [] });
const labExperimentData = ref<Partial<Experiment>>({});
const labPlatformData = ref<Partial<LabPlatformVO>>({});
const formattedTime = ref("00 小时 00 分钟 00 秒");
const errorformVisible = ref(false);
const Ext = ref({
  controlList: [],
  settingList: [],
  ConfigPercentage: 0
});
const ConfigPercentage = ref(0);
const runPercentage = ref(0);
const runingExpIns = useExpInsHook();

// const format = percentage => (percentage === 100 ? "Full" : `${percentage}%`);
const formDialogVisible = ref(false);

defineOptions({
  name: "Monitor"
});

const settingLR: ContextProps = reactive({
  minPercent: 2,
  defaultPercent: 80,
  split: "vertical"
});

const loading = ref<boolean>(true);
const contorDialogVisible = ref(false);

const settingList = ref<SettingIF[]>([]);
const controlList = ref<ContorDevice[]>([]);

let timerSensor = null;
let timer = null; //记录时间

const obj = { name: "11", age: 2 };
const p1 = new Proxy(obj, {
  get(target, p, receiver) {
    return obj[p];
  },
  set(target, p, value) {
    obj[p] = value;
  }
});

const fetchData = async () => {
  if (!expInstId.value && !configId.value) {
    // ElMessage.error("请选择具体实例");
    return;
  }
  const deviceStatus = await listDeviceStatus();

  //获取实验配置
  try {
    const labPlatformRes = await getPlatform(configId.value);
    if (labPlatformRes.data.sensors) {
      labPlatformRes.data.sensors.forEach(sensor => {
        const foundData = deviceStatus.data.find(
          item => item.deviceId === sensor.deviceId
        );
        if (foundData) {
          sensor.displayVal = foundData.displayVal;
          sensor.origValue = foundData.origValue;
          sensor.unit = foundData.unit;
          sensor.onlineState = foundData.onlineState;
        }

        if (sensor.ext) {
          try {
            sensor.ext = JSON.parse(String(sensor.ext));
          } catch (error) {
            return;
          }
        }
      });
    }
    labPlatformData.value = labPlatformRes.data;
  } catch (error) {
    console.log(error);
  }

  //如果实验实例ID存在，则获取实验实例数据
  if (expInstId.value) {
    try {
      console.log("getExperiment");
      const labExpRes = await getExperiment(expInstId.value as string);
      if (labExpRes.data.sensors) {
        labExpRes.data.sensors.forEach(sensor => {
          const foundData = deviceStatus.data.find(
            item => item.deviceId === sensor.deviceId
          );
          if (foundData) {
            sensor.origValue = foundData.origValue;
            sensor.unit = foundData.unit;
            sensor.onlineState = foundData.onlineState;
          }

          if (sensor.ext) {
            try {
              sensor.ext = JSON.parse(String(sensor.ext));
            } catch (error) {
              return;
            }
          }
        });
      }
      labExperimentData.value = labExpRes.data;
    } catch (error) {
      console.log(error);
    }
  }
};

// const clearCache = key => {
//   localStorage.removeItem(key);
// };

const setCache = (key, value) => {
  //构造一个key为key，value为value的对象
  // const item = {
  //   [key]: value
  // };
  Ext.value[key] = value;

  // Ext = { ...Ext, ...item };
  // console.log(Ext);
  // localStorage.setItem(key, JSON.stringify(item));
};

const saveExt = async () => {
  if (configFlag.value == "1") {
    console.log("saveExt");
    // if (configFlag.value == "1" || labExperimentData.value.state == "10") {
    const result = await getPlatform(configId.value);
    console.log(Ext.value);
    console.log(JSON.stringify(Ext.value));

    const data = {
      ...result.data,
      ExpId: configId.value,
      Ext: JSON.stringify(Ext.value)
    };
    const ret = await updatePlatform(data);
    if (!ret.errorCode) {
      // message(`保存成功`, { type: "success" });
    } else {
      // message(`保存失败，${ret.message}`, { type: "error" });
    }
  } else if (expFlag.value == "1" || hisFlag.value == "1") {
    // console.log("saveExt1111111111111");
    const result = await getExperiment(expInstId.value as string);
    console.log(Ext.value);
    console.log(JSON.stringify(Ext.value));

    const data = {
      ...result.data,
      id: expInstId.value,
      Ext: JSON.stringify(Ext.value)
    };
    const ret = await updateInstanceExt(data);
    if (!ret.errorCode) {
      // message(`保存成功`, { type: "success" });
    } else {
      // message(`保存失败，${ret.message}`, { type: "error" });
    }
  }

  // }
  await fetchData();
};

// const getExt = async () => {
//   if (configFlag.value == "setconfig") {
//     const result = await getPlatform(configId.value);
//     if (result.data) {
//       try {
//         const jsonExt = JSON.parse(result.data.ext);
//         console.log("jsonExt", jsonExt);
//         Ext.value.controlList = jsonExt.controlList;
//         Ext.value.settingList = jsonExt.settingList;
//         return jsonExt;
//         // console.log("EXT", Ext);
//       } catch (error) {
//         return;
//       }
//     }
//   }
// };

const controlInit = () => {
  const LocalControlList = Ext.value.controlList;
  if (LocalControlList) {
    controlList.value = LocalControlList;
  } else {
    return;
  }
};

const settingInit = () => {
  const LocalSettingList = Ext.value.settingList;
  if (LocalSettingList) {
    settingList.value = LocalSettingList;
  } else {
    return;
  }
};

const setTimerSensor = () => {
  // clearInterval(timerSensor);
  // timer = null;
  fetchData();
};

const setTimer = () => {
  // clearInterval(timer);
  // timer = null;

  const currentTime = new Date();
  if (
    currentTime.getTime() > new Date(labExperimentData.value.endTime).getTime()
  ) {
    clearInterval(timer);
    timer = null;
    return;
  }
  const timeDiff =
    currentTime.getTime() -
    new Date(labExperimentData.value.startTime).getTime();
  if (timeDiff < 0) {
    return;
  }

  const alltime =
    new Date(labExperimentData.value.endTime).getTime() -
    new Date(labExperimentData.value.startTime).getTime();

  if (timeDiff > alltime) {
    clearInterval(timer);
    timer = null;
    labExperimentData.value.state = 20;
    return;
  }
  runPercentage.value = Number(((timeDiff / alltime) * 100).toFixed(2));
  // 计算小时、分钟和秒数
  const hours = Math.floor(timeDiff / (1000 * 60 * 60));
  const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

  // 格式化时间
  formattedTime.value = `${hours} 小时 ${
    minutes < 10 ? "0" + minutes : minutes
  } 分钟 ${seconds < 10 ? "0" + seconds : seconds} 秒`;
  console.log("ConfigPercentage", ConfigPercentage);
};

onMounted(async () => {
  timerSensor = setInterval(setTimerSensor, 5000); //刷新传感器
  if (configFlag.value != "1" && hisFlag.value != "1") {
    //如果不是设置，也不是历史，那么执行以下内容
    const defaultMonitorQuery = JSON.parse(
      localStorage.getItem("defaultMonitorQuery")
    );
    //如果defaultMonitorQuery存在，那么就获取ID数据
    if (defaultMonitorQuery) {
      configId.value = defaultMonitorQuery.configId;
      // expInstName.value = defaultMonitorQuery.name;
      expInstId.value = defaultMonitorQuery.id;
      configFlag.value = defaultMonitorQuery.configFlag;
      hisFlag.value = defaultMonitorQuery.hisFlag;
      expFlag.value = defaultMonitorQuery.expFlag;
    }

    //获取正在运行的实例，如果有正在运行的，那就获取其ID
    const result = await getRunningExperiments();
    if (!result.errorCode) {
      if (result.data) {
        configId.value = result.data.expPlatformId;
        // expInstName.value = result.data.name;
        expInstId.value = result.data.id;
      }
    } else {
      message(`${result.message}`, { type: "error" });
    }
    console.log(expInstId.value);
    // errorformVisible.value = !expInstId.value ? true : false;
  }
  //获取Ext，解析到本地
  //获取实验平台/配置

  let result = {};

  console.log({
    // expInstName: expInstName.value,
    expInstId: expInstId.value,
    configId: configId.value,
    configFlag: configFlag.value,
    hisFlag: hisFlag.value,
    expFlag: expFlag.value
  });

  if (configFlag.value == "1") {
    result = await getPlatform(configId.value);
    console.log("EXTResult实验配置", result);
  } else if (hisFlag.value == "1" || expFlag.value == "1") {
    result = await getExperiment(expInstId.value as string);
    console.log("！！EXTResult实验实例", result);
    console.log(result.data.ext);
  }
  if (result.data) {
    try {
      //获取Ext
      console.log(result.data.ext);
      const jsonExt = JSON.parse(result.data.ext);

      Ext.value.controlList = jsonExt.controlList;
      Ext.value.settingList = jsonExt.settingList;
      Ext.value.ConfigPercentage = jsonExt.ConfigPercentage;
    } catch (error) {
      return;
    }
  } else {
    console.log("未获取", result);
  }
  //获取上次记录的进度值
  ConfigPercentage.value = Number(Ext.value.ConfigPercentage);

  settingInit();
  controlInit();

  // alert(configId.value);
  if (
    //如果配置都没有，那么就提示
    settingList.value.length == 0 &&
    controlList.value.length == 0 &&
    configId.value != ""
  ) {
    message(`请添加设备或控制器`, { type: "warning" });
  }
  //前面是获取谁的数据
  //获取数据
  await fetchData();
  clearInterval(timer);

  //实验状态
  if (labExperimentData.value.state === 10) {
    timer = setInterval(setTimer, 1000);
  }

  if (labExperimentData.value.state === 20) {
    const currentTime = new Date();

    //获取实验起始时间
    const timeDiff =
      new Date(labExperimentData.value.endTime).getTime() -
      new Date(labExperimentData.value.startTime).getTime();
    if (timeDiff < 0) {
      return;
    }
    // 计算小时、分钟和秒数
    const hours = Math.floor(timeDiff / (1000 * 60 * 60));
    const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

    // 格式化时间
    formattedTime.value = `${hours} 小时 ${
      minutes < 10 ? "0" + minutes : minutes
    } 分钟 ${seconds < 10 ? "0" + seconds : seconds} 秒`;
  }
});

const addNewChart = () => {
  settingList.value.push({
    key: String(new Date().getTime()),
    id: labExperimentData.value.id || "",
    name: `默认图表${settingList.value.length}` || "",
    duration: "3600",
    startTime: "",
    optionY: [
      { name: "Y1", mesure: "", unit: "", sensors: [] },
      { name: "Y2", mesure: "", unit: "", sensors: [] }
    ]
  });
  ConfigPercentage.value += 20;
  ConfigPercentage.value = Math.max(0, ConfigPercentage.value); // 将值限制在0以上
  ConfigPercentage.value = Math.min(100, ConfigPercentage.value); // 将值限制在100以下
  saveExt();
};

const addNewExp = () => {
  formDialogVisible.value = true;
};

const handleDeleteItem = currentIndex => {
  ElMessageBox.confirm(`确认删除默认图表${currentIndex}`, "提示", {
    type: "warning"
  })
    .then(async () => {
      for (let i = 0; i < 2; i++) {
        for (const sensor of settingList.value[currentIndex].optionY[i]
          .sensors) {
          await removeExpDevice({
            expId: configId.value,
            deviceId: sensor.deviceId
          });
          // await addPlatformDevice({
          //   expId: props.configId,
          //   deviceId: sensor.deviceId,
          //   interval: sensor.period
          // });
        }
      }

      settingList.value = settingList.value.filter((item, index) => {
        return index != currentIndex;
      });
      ElMessage.success("删除成功");
      ConfigPercentage.value -= 20;
      ConfigPercentage.value = Math.max(0, ConfigPercentage.value); // 将值限制在0以上
      ConfigPercentage.value = Math.min(100, ConfigPercentage.value); // 将值限制在100以下
      saveExt();
    })
    .catch(() => {});
};

const handleDeleteContor = currentID => {
  ElMessageBox.confirm(`确认删除控制器`, "提示", {
    type: "warning"
  })
    .then(async () => {
      await removeExpDevice({
        expId: configId.value,
        deviceId: currentID
      });
      controlList.value = controlList.value.filter(item => {
        return item.deviceId != currentID;
      });
      ElMessage.success("删除成功");
      ConfigPercentage.value -= 20;
      ConfigPercentage.value = Math.max(0, ConfigPercentage.value); // 将值限制在0以上
      ConfigPercentage.value = Math.min(100, ConfigPercentage.value); // 将值限制在100以下
      saveExt();
    })
    .catch(() => {});
};

const clickStartExp = async () => {
  if (labExperimentData.value.state === 0) {
    ElMessageBox.confirm(
      `确定开始实例${labExperimentData.value.name}`,
      "提示",
      {
        type: "warning"
      }
    )
      .then(async () => {
        const ret = await startInstance(labExperimentData.value.id);
        if (!ret.errorCode) {
          labExperimentData.value.state = 10;
        } else {
          message(`启动失败，${ret.message}`, { type: "error" });
        }

        await fetchData();
        timer = setInterval(setTimer, 1000);
        ElMessage.success("开始实例");
      })
      .catch(() => {});
  } else if (labExperimentData.value.state === 10) {
    ElMessageBox.confirm(
      `确定停止实例${labExperimentData.value.name}`,
      "提示",
      {
        type: "warning"
      }
    )
      .then(async () => {
        const ret = await stopInstance(labExperimentData.value.id);
        if (!ret.errorCode) {
          labExperimentData.value.state = 20;
        } else {
          message(`停止失败，${ret.message}`, { type: "error" });
        }
        clearInterval(timer);
        timer = null;
        fetchData();
        ElMessage.success("停止实例");
      })
      .catch(() => {});
  }
};

onUpdated(() => {
  console.log("updated");
  setCache(`settingList`, settingList.value);
  setCache(`controlList`, controlList.value);
  setCache(`ConfigPercentage`, ConfigPercentage.value);

  // saveExt()
  // localStorage.setItem(`settingList${expInstId.value}`, JSON.stringify(item));
  // localStorage.setItem(
  //   `controlList${expInstId.value}`,
  //   JSON.stringify(controlList.value)
  // );
});
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
  if (timerSensor) {
    clearInterval(timerSensor);
    timerSensor = null;
  }
});
// onBeforeUnmount(() => {
//   saveExt();
// });
setTimeout(() => {
  loading.value = !loading.value;
}, 800);
controlList;
const routerTo = (tempname, tempquery) => {
  router.push({
    name: tempname,
    query: tempquery
  });
};
const exportLoading = ref(false);
const exportExp = () => {
  exportLoading.value = true;
  downloadInstanceData({
    expInstId: labExperimentData.value.id
  }).then(response => {
    console.log("response", response);
    if (response.errorCode || !response) {
      message(`导出失败：${response.message}`, { type: "error" });
      exportLoading.value = false;

      return;
    }

    const blob = new Blob([response], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
    });
    const fileName = `${labExperimentData.value.name}_${labExperimentData.value.id} ${formattedTime.value}_实验数据.xlsx`;
    if ("download" in document.createElement("a")) {
      // 非IE下载
      const elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName);
    }
    exportLoading.value = false;
  });
};

watch(
  () => runPercentage.value,
  newVal => {
    console.log("formattedTime", newVal);

    runingExpIns.changeSetting({
      key: "configPercentage",
      value: runPercentage.value
    });
    runingExpIns.changeSetting({
      key: "formattedTime",
      value: formattedTime.value
    });
    runingExpIns.changeSetting({
      key: "labExperimentDatastate",
      value: labExperimentData.value.state
    });
    runingExpIns.changeSetting({
      key: "configId",
      value: configId.value
    });
    runingExpIns.changeSetting({
      key: "expInstId",
      value: expInstId.value
    });
  }
);

const handleClose = () => {
  routerTo("Expconfig", {});
  errorformVisible.value = false;
};

// const cache = () => {
//   console.log("Cache Cleared");
// };
// const alert = () => {
//   console.log("Cache ");

//   // alert("Clicked on alert icon");
// };
</script>

<template>
  <!-- 实验平台：{{ labPlatformData }}
  <div style="margin-top: 30px" />

  实验实例：{{ labExperimentData }}
  <div style="margin-top: 30px" />

  Ext：{{ Ext }}
  <div style="margin-top: 30px" />

  expInstId：{{ expInstId }}
  <div style="margin-top: 30px" />
  {{ controlList }}

  {{ hisFlag }} -->
  <dialogFormNew
    v-model:visible="formDialogVisible"
    :configId="configId"
    :ext="Ext"
  />

  <a-float-button-group
    trigger="hover"
    type="primary"
    :style="{ right: '24px' }"
    v-if="configFlag == '1' || labExperimentData.state == 0"
  >
    <template #icon>
      <IconifyIconOnline icon="material-symbols:add" />
    </template>
    <a-float-button tooltip="新增图表" @click="addNewChart">
      <template #icon>
        <IconifyIconOnline icon="material-symbols:table-chart-view-outline" />
      </template>
    </a-float-button>
    <a-float-button tooltip="新增控制器" @click="contorDialogVisible = true">
      <template #icon>
        <IconifyIconOnline icon="material-symbols:computer-outline-rounded" />
      </template>
    </a-float-button>
  </a-float-button-group>
  <el-dialog
    title="提示信息"
    @close="handleClose()"
    v-model="errorformVisible"
    :modal="true"
  >
    <span>请选择正确的实验配置</span>
  </el-dialog>

  <div style="padding-top: 8px; padding-left: 8px">
    <span class="font-medium" style="display: none">{{ settingList }}</span>
    <span class="font-medium" style="display: none"> {{ controlList }} </span>

    <el-row
      style="
        background-color: white;
        margin-bottom: 10px;
        margin-right: 10px;
        padding: 8px 25px;
      "
      justify="space-around"
      align="middle"
    >
      <el-col :span="6">
        <div style="display: flex; align-items: center">
          <el-image
            style="border-radius: 50%; width: 40px; height: 40px"
            src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
          />
          <div
            style="
              display: flex;
              flex-direction: column;
              margin-left: 40px;
              align-items: flex-start;
            "
          >
            <div>
              <el-text size="large" style="font-weight: bold">{{
                labPlatformData.name
              }}</el-text>
            </div>
            <div>
              <el-text>{{ labExperimentData.name }}</el-text>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <!-- <div>配置中</div> -->
        <div
          v-if="configFlag == '1'"
          style="display: flex; justify-content: center"
        >
          <el-text>配置中...</el-text>

          <div style="width: 80%; margin-left: 10px">
            <el-progress
              :percentage="100"
              striped
              color="#E6A23C"
              status="warning"
            />
          </div>
        </div>
        <div
          v-else-if="labExperimentData.state == 0"
          style="display: flex; justify-content: center"
        >
          <el-text>未开始</el-text>

          <div style="width: 80%; margin-left: 10px">
            <el-progress
              :percentage="100"
              striped
              color="#E6A23C"
              status="warning"
            />
          </div>
        </div>
        <div
          v-else-if="labExperimentData.state == 10"
          style="display: flex; flex-direction: column"
        >
          <div>
            <el-text size="small">{{ formattedTime }}</el-text>
          </div>
          <div style="width: 80%">
            <el-progress :percentage="runPercentage" color="#67C23A" />
          </div>
        </div>
        <div
          v-else-if="labExperimentData.state == 20 && hisFlag != '1'"
          style="display: flex; flex-direction: column"
        >
          <div>
            <el-text size="small">已结束</el-text>
          </div>
          <div style="width: 80%">
            <el-progress :percentage="100" status="success" />
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div style="display: flex; justify-content: end">
          <el-button
            v-if="configFlag == '1'"
            :icon="useRenderIcon(AddFill)"
            @click="addNewExp()"
            >创建实验</el-button
          >
          <el-button
            type="primary"
            v-else-if="
              labExperimentData.state == 0 &&
              (Ext.settingList.length > 0 || Ext.controlList.length > 0)
            "
            :icon="VideoPlay"
            @click="clickStartExp()"
            >开始实验</el-button
          >
          <el-button
            v-if="
              (expFlag == '1' && labExperimentData.state == 10) ||
              hisFlag == '1'
            "
            :loading="exportLoading"
            :icon="FolderOpened"
            @click="exportExp()"
            >导出数据</el-button
          >
          <el-button
            type="danger"
            v-if="labExperimentData.state == 10"
            :icon="SwitchButton"
            @click="clickStartExp()"
            >结束实验</el-button
          >
        </div>
      </el-col>
    </el-row>
    <!-- </div> -->

    <div class="split-pane">
      <splitpane :splitSet="settingLR">
        <!-- #paneL 表示指定该组件为左侧面板 -->
        <template #paneL>
          <el-col>
            <el-card
              shadow="never"
              class="box-card"
              v-for="(setting, index) in settingList"
              :key="setting.key"
            >
              <el-skeleton animated :rows="7" :loading="loading">
                <template #default>
                  <!-- {{ labExperimentData.state }} -->
                  <Line
                    @data-confirm-click="saveExt()"
                    v-model:settingLine="settingList[index]"
                    :expState="labExperimentData.state"
                    :labExperimentData="labExperimentData"
                    :currentIndex="index"
                    :expInstId="String(expInstId)"
                    :configId="String(configId)"
                    :hisFlag="hisFlag"
                    @delete-item="handleDeleteItem"
                    v-if="expState !== ''"
                  />
                </template>
              </el-skeleton>
            </el-card>
          </el-col>
          <div>
            <div
              class="card-header box-card"
              style="padding: 20px; margin-top: 10px"
            >
              <Contor
                @data-confirm-click="saveExt()"
                @delete-item="handleDeleteContor"
                v-model:controlList="controlList"
                :expData="labExperimentData"
              />
            </div>
          </div>
        </template>

        <!-- #paneR 表示指定该组件为右侧面板 -->
        <template #paneR>
          <el-col style="height: 100%">
            <div class="message-container">
              <el-tabs class="demo-tabs" model-value="devices">
                <el-tab-pane label="设备状态" name="devices">
                  <el-scrollbar height="100%">
                    <div
                      v-for="(sensor, index) in labPlatformData.sensors"
                      :key="index"
                    >
                      <div
                        style="
                          display: flex;
                          padding: 10px 20px;
                          align-items: center;
                        "
                      >
                        <el-tag
                          :type="
                            sensor.onlineState === 1 ? 'success' : 'danger'
                          "
                          size="small"
                          >{{
                            sensor.onlineState === 1 ? "已连接" : "未连接"
                          }}</el-tag
                        >

                        <el-tooltip placement="top">
                          <template #content>{{ sensor.name }}</template>
                          <text
                            style="
                              white-space: nowrap;
                              overflow: hidden;
                              text-overflow: ellipsis;
                              margin-left: 10px;
                            "
                            size="small"
                            class="w-10px"
                            truncated
                            >{{ sensor.name }}</text
                          >
                        </el-tooltip>

                        <span style="margin-left: auto" />
                        <div>
                          {{ sensor.displayVal ? sensor.displayVal : "NULL"
                          }}{{
                            sensor.unit === "Celsius"
                              ? "℃"
                              : sensor.unit === "Percent"
                              ? "%"
                              : sensor.unit
                          }}
                        </div>
                      </div>

                      <el-divider />
                    </div>
                  </el-scrollbar>
                </el-tab-pane>
                <el-tab-pane label="其他" name="other" />
              </el-tabs>
            </div>
          </el-col>
        </template>
      </splitpane>
    </div>
  </div>
  <contordialog
    @data-confirm-click="saveExt()"
    v-model:visible="contorDialogVisible"
    :expData="labExperimentData"
    :configId="configId"
    v-model:controlList="controlList"
    v-model:ConfigPercentage="ConfigPercentage"
  />
</template>

<style lang="scss" scoped>
$W: 100%;
$H: calc(100vh - 64px);

.demo-progress .el-progress--line {
  margin-bottom: 15px;
  max-width: 600px;
}
:deep(.el-timeline-item) {
  margin: 6px 0 0 6px;
}

.main-content {
  margin: 8px !important;
}
.card-header {
  display: flex;
  align-items: center;
  background-color: white;
}

.message-container {
  background-color: white;
  margin-right: 10px;
  height: 100%;
}

.split-pane {
  width: $W;
  height: $H;
}

.box-card {
  margin-bottom: 8px;
}

.box-card-device {
  padding: none !important;
  border: none;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

:deep(.el-drawer__header) {
  margin-bottom: 10px !important;
}

:deep(.el-tabs--top .el-tabs__item.is-top:nth-child(2)) {
  padding-left: 20px;
}
</style>
